package com.example.furniture.controller;

import com.example.furniture.dto.AiChatRequest;
import com.example.furniture.dto.AiChatResponse;
import com.example.furniture.service.AiChatService;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * AI对话控制器
 * 提供AI对话相关的API接口
 *
 * @author 家具商城系统
 * @version 1.0
 * @since 2024-01-01
 */
@RestController
@RequestMapping("/ai")
@CrossOrigin(origins = "*")
public class AiChatController {

    private static final Logger logger = LoggerFactory.getLogger(AiChatController.class);
    private final AiChatService aiChatService;

    /**
     * 构造函数，注入AI对话服务
     *
     * @param aiChatService AI对话服务实例
     */
    public AiChatController(AiChatService aiChatService) {
        this.aiChatService = aiChatService;
    }

    /**
     * 发送消息给AI
     *
     * @param chatRequest 对话请求
     * @return AI回复
     */
    @PostMapping("/chat")
    public ResponseEntity<Map<String, Object>> chat(@Valid @RequestBody AiChatRequest chatRequest) {
        try {
            logger.info("AI对话请求: {}", chatRequest.getMessage());

            AiChatResponse response = aiChatService.chat(chatRequest);

            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "对话成功");
            result.put("data", response);
            result.put("timestamp", System.currentTimeMillis());

            logger.info("AI对话成功");
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            logger.error("AI对话失败", e);

            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "对话失败: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 健康检查
     *
     * @return 健康状态
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> health() {
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "AI对话服务正常运行");
        result.put("timestamp", System.currentTimeMillis());

        return ResponseEntity.ok(result);
    }
}